from flask import Blueprint,jsonify
from flask_restful import request
import time,random
from util.myredis import r
from models import *
chongzhi_blue = Blueprint('chongzhi_blue',__name__)
from util.comm import get_ali_object


@chongzhi_blue.route('/chongzhi')
def chongzhi():
    alipay = get_ali_object()
    # 生成支付的url
    userid = int(request.args.get('userid'))
    money = request.args.get('money')
    order_num = str(userid) + str(random.randint(10000, 99999))
    res = IvnestModel(userid=userid,money=money,order_number=order_num,status=1)
    res.create()
    key = 'czyanshiduilie'
    exptime = int(time.time()) + 1800
    r.sortedset_add(key,order_num,exptime)
    query_params = alipay.direct_pay(
        subject=str(userid) + '用户充值',  # 商品简单描述
        out_trade_no=order_num,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=money,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code':200,'url':pay_url})

@chongzhi_blue.route('/callback')
def callback():
    # "ImmutableMultiDict([('charset', 'utf-8'), ('out_trade_no', '192066'), ('method', 'alipay.trade.page.pay.return'), ('total_amount', '1.00'), ('sign', 'JSdzC1RspUba7rqHAK4FcDXSJjivWp5WLsRz9WGHc7dIM3954ASD41n8QpQHEW0gmJfgvEblgIEQrXKjdSzApnbAK7JON4jRf+u0WCU64Y5Gcz5DAXaIhMBhNH8w1PIxQIEJ0Ov1kdk7p/Ptyef1suIT3s3N92GYK/RjZTdFEyvQBpwUvObiEk7WPBNEf9l3D4M94qdiRXfWULhITv32K03U6U4l6vRn3DhgHlSR8v09hH91q1RcaVHBUWUTeOdhKoRwvWAkN8xdBUykEmJfAVe0LjmmlR5v7ehRy39EdNzrfdlukNSnRdH2pE3HXQEJyJz2NaC4JrDRJQymfe2Meg=='), ('trade_no', '2023031422001433170503912465'), ('auth_app_id', '2021000121656802'), ('version', '1.0'), ('app_id', '2021000121656802'), ('sign_type', 'RSA2'), ('seller_id', '2088621993086880'), ('timestamp', '2023-03-14 20:09:50')])
    # 接收参数
    data = request.args.to_dict()
    # 处理参数

    print(data)
    print(data['total_amount'])
    money = data['total_amount']
    aa = data['out_trade_no']
    r.sortedset_delete('czyanshiduilie', aa)
    # 将签名单独拿出
    sign = data.pop('sign')
    alipay = get_ali_object()
    #调用支付宝接口验签
    flag = alipay.verify(data, sign)
    res = IvnestModel.query.filter(IvnestModel.order_number==aa).first()
    userid = res.userid
    if flag==True:
        res = IvnestModel.query.filter(IvnestModel.order_number==aa).first()
        res.status=2
        res = UserModle.query.filter(UserModle.id==userid).first()
        res.money = float(res.money) + float(money)
        res = AccountModel(userid=userid,order_number=aa,desc='往猪八戒平台充值',money=money)
        res.create()
        # res.upd()
    return jsonify({'code':200,'msg':'okook'})